﻿using AutoMapper;
using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.TaskRob;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Dto;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helper;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace H2.NET.Web.Pages.SMD
{
    public partial class BatchDevice : BasePage
    {
        public IList<t_StoreDataChangeLog> logs = new List<t_StoreDataChangeLog>();

        public string update_logs = "[]";

        public string stores_json = "[]";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (ReadOnly()) return;

                Session.Remove("StoreDataChangeLog_Device");

                InitDropDownList();

                if (IsOverFlow)
                {
                    btn_submit.Visible = false;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.tip('" + string.Format("该表单正在被“{0}”处理，请稍后再试。", RobUser) + "', 'info');", true);
                    return;
                }
                btn_submit.Visible = TaskAPI.IsAllowSubmit;
                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");

                #region Submit Data
                if (TaskAPI.Step == "Submit Data")
                {
                    if (Session["StoreDataChangeLog_Device"] != null)
                    {
                        var sdc_logs = Session["StoreDataChangeLog_Device"] as List<t_StoreDataChangeLog>;

                        Mapper.CreateMap<t_StoreDataChangeLog, StoreDataChangeLogDto>();
                        var list = Mapper.Map<List<t_StoreDataChangeLog>, List<StoreDataChangeLogDto>>(sdc_logs);
                        IsoDateTimeConverter iso = new IsoDateTimeConverter();
                        iso.DateTimeFormat = "yyyy-MM-dd";
                        update_logs = JsonConvert.SerializeObject(list, iso);
                    }
                    if (!String.IsNullOrEmpty(TaskAPI.GetVariableBySingleValue("Checked")))
                    {
                        assessment.Visible = true;
                    }
                }
                #endregion

                #region 审批环节
                else
                {

                    #region 加载数据并显示
                    var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                    if (storeMasterData == null)
                    {
                        btn_submit.Visible = false;
                        JsTip("加载数据失败，请关闭页面重新打开！");
                        return;
                    }

                    hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                    hl_ExportPdf.Visible = true;

                    uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                    assessment.Visible = true;

                    var assessments = (t_Assessment.process == TaskAPI.Process
                        & t_Assessment.incident == TaskAPI.Incident).List<t_Assessment>();

                    logs = (t_StoreDataChangeLog._AssessmentID.In(assessments.Select(t => t.ID))).List<t_StoreDataChangeLog>(null, " logid desc ");
                    var result_logs = logs.Distinct(new StoreDataChangeLogComparer()).ToList();
                    Session["StoreDataChangeLog_Device"] = logs;

                    var dataIds = logs.Select(t => Convert.ToInt32(t.DataID)).Distinct();
                    var devices = (t_smd_Device._DeviceID.In(dataIds)).List<t_smd_Device>(Storage.Context3).ToList();
                    for (int i = 0; i < devices.Count; i++)
                    {
                        devices[i] = DataHelper<t_smd_Device>.Reload(devices[i],
                                result_logs.Where(t => t.DataID == devices[i].DeviceID.ToString()).ToList());
                    }

                    Mapper.CreateMap<t_smd_Device, DeviceDto>();
                    var list = Mapper.Map<List<t_smd_Device>, List<DeviceDto>>(devices);
                    IsoDateTimeConverter iso = new IsoDateTimeConverter();
                    iso.DateTimeFormat = "yyyy-MM-dd";
                    stores_json = JsonConvert.SerializeObject(list, iso);
                    #endregion

                    #region 审批项初始化
                    switch (TaskAPI.Step)
                    {
                        case "Data Check":
                            DwzAssessment1.Option.Add(new t_AssessmentOption("通过", "1", true));
                            DwzAssessment1.Option.Add(new t_AssessmentOption("退回", "0", false));
                            break;
                        case "Manager Approve":
                            DwzAssessment1.Option.Add(new t_AssessmentOption("通过", "1", true));
                            DwzAssessment1.Option.Add(new t_AssessmentOption("退回", "0", false));
                            break;
                        case "DMO Commit":
                            DwzAssessment1.Option.Add(new t_AssessmentOption("通过", "1", true));
                            DwzAssessment1.Option.Add(new t_AssessmentOption("退回", "0", false));
                            break;
                    }
                    #endregion

                    
                    lb_selectData.Visible = false;
                }
                #endregion

                InitUpdateLogs();
            }
        }


        #region 只读表单

        private bool ReadOnly()
        {
            if (AksRequest.GetString("readonly") == "1")
            {
                // 只读表单，释放抢占
                OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);

                lb_selectData.Visible = false;
                assessment.Visible = true;
                btn_submit.Visible = false;
                DwzAssessment1.Visible = false;

                #region 加载数据并显示
                // 门店数据
                var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                if (storeMasterData == null)
                {
                    JsTip("该流程还没有提交过，没有任何数据！");
                    return true;
                }

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");

                assessment.Visible = true;

                var assids = AssessmentService.GetIdsByTaskApi(TaskAPI);

                logs = (t_StoreDataChangeLog._AssessmentID.In(assids)).List<t_StoreDataChangeLog>(null, " logid desc ");
                var result_logs = logs.Distinct(new StoreDataChangeLogComparer()).ToList();
                Session["StoreDataChangeLog_Device"] = logs;

                var dataIds = logs.Select(t => Convert.ToInt32(t.DataID)).Distinct();
                var devices = (t_smd_Device._DeviceID.In(dataIds)).List<t_smd_Device>(Storage.Context3).ToList();
                for (int i = 0; i < devices.Count; i++)
                {
                    devices[i] = DataHelper<t_smd_Device>.Reload(devices[i],
                            result_logs.Where(t => t.DataID == devices[i].DeviceID.ToString()).ToList());
                }

                Mapper.CreateMap<t_smd_Device, DeviceDto>();
                var list = Mapper.Map<List<t_smd_Device>, List<DeviceDto>>(devices);
                IsoDateTimeConverter iso = new IsoDateTimeConverter();
                iso.DateTimeFormat = "yyyy-MM-dd";
                stores_json = JsonConvert.SerializeObject(list, iso);
                #endregion

                InitUpdateLogs();

                hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                hl_ExportPdf.Visible = true;
                btn_print.Visible = true;

                return true;
            }

            return false;
        }
        #endregion

        private bool Send(ref string return_msg)
        {
            bool flag = false;
            try
            {
                #region 数据验证
                if (TaskAPI.Step == "Submit Data" && TaskAPI.IsAllowSubmit) // 如果是退回的情况，不存在验证
                {
                    if (Session["StoreDataChangeLog_Device"] == null)
                    {
                        return_msg = "至少选择修改一项";
                        return false;
                    }
                }
                if (DwzAssessment1.Assessment.Remark == "")
                {
                    if (DwzAssessment1.Assessment.Opinion == "2") { 
                        return_msg = "如果驳回此流程,请在状态备注中填写放弃流程的原因";
                        return false;
                    }
                    if (DwzAssessment1.Assessment.Opinion == "0") 
                    {
                        return_msg = "如果退回此流程,请在状态备注中填写退回的原因";
                        return false;
                    }
                }
                #endregion

                #region 引擎传值
                if (TaskAPI.Step == "Submit Data")
                {
                    TaskAPI["IsBatch"] = "批量";
                    TaskAPI["Remark_by_Initiator"] = DwzAssessment1.Assessment.Remark;
                    TaskAPI.Summary = "设备信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary);
                }
                else
                {
                    TaskAPI["ApproveResult"] = DwzAssessment1.Assessment.Opinion;
                    TaskAPI["TaskID"] = TaskAPI.TaskID;
                    if (TaskAPI.Step == "Data Check")
                    {
                        TaskAPI["Checked"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            TaskAPI.Summary = "设备信息CSM审核/" + TaskHelper.getSummary(TaskAPI.Summary);
                        }
                        else
                        {
                            TaskAPI.Summary = "(退回)提交设备信息变更/" + TaskHelper.getSummary(TaskAPI.Summary);
                        }
                    }
                    if (TaskAPI.Step == "Manager Approve")
                    {
                        TaskAPI["Approved"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            TaskAPI.Summary = "设备变更DMO导入核查/" + TaskHelper.getSummary(TaskAPI.Summary);
                        }
                        else
                        {
                            TaskAPI.Summary = "(退回)设备信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary);
                        }
                    }
                    else if (TaskAPI.Step == "DMO Commit")
                    {
                        return_msg = "数据更新到主数据库中时出现错误，请跟踪并处理。";
                        TaskAPI["Commited"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "0")
                        {
                            TaskAPI.Summary = "(退回)设备信息CSM审核/" + TaskHelper.getSummary(TaskAPI.Summary);
                        }
                    }
                }

                #endregion

                #region 提交步骤

                string step = string.Empty;
                Storage.TransactionExecute(o =>
                {
                    #region 业务流程、审批意见记录

                    t_Assessment ass = DwzAssessment1.Assessment;
                    var lastAss = (t_Assessment.incident == TaskAPI.Incident & t_Assessment.process == TaskAPI.Process).ListFirst<t_Assessment>("time desc");
                    if ((lastAss != null && lastAss.Step != TaskAPI.Step) || lastAss == null)
                    {
                        Storage.Save(Storage.Context1, ass);
                    }
                    else
                    {
                        Logging.GetLogger().Info("=================表单已重复提交======================");
                        Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                        Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                        Logging.GetLogger().Info("时间：" + DateTime.Now);
                        Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                        Logging.GetLogger().Info("======================================================");
                        throw new Exception("该表单的步骤已经提交过了，请联系IT。");
                    }
                    var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                    #endregion

                    #region “Submit Data”步骤
                    if (TaskAPI.Step == "Submit Data")
                    {
                        t_StoreMasterData storeMasterData = new t_StoreMasterData();
                        storeMasterData.SubmitDate = DateTime.Now;
                        storeMasterData.Creator = TaskAPI.UserName;
                        storeMasterData.ApplicationNO = uc_head1.applicationNo;
                        storeMasterData.Process = TaskAPI.Process;
                        storeMasterData.Incident = TaskAPI.Incident;
                        storeMasterData.BusinessProcess = ass.BusinessProcess;
                        storeMasterData.BusinessKey = ass.BusinessKey;
                        Storage.Save(Storage.Context1, storeMasterData);

                        var storeDataChangeLogs = Session["StoreDataChangeLog_Device"] as List<t_StoreDataChangeLog>;
                        storeDataChangeLogs.ForEach(log => log.AssessmentID = ass.ID);
                        Storage.Save(storeDataChangeLogs.ToArray());

                        if (key.Equals(Constant.PROCESS_CHANGEOTHER))
                        {
                            BusinessService.SaveChildProcess(TaskAPI, ass, "active");

                            var devices = new List<t_smd_Device>();
                            var stores = new List<t_smd_Store>();
                            var dealers = new List<t_smd_Dealer>();

                            foreach (var log in storeDataChangeLogs)
                            {
                                var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(log.DataID, 0));
                                var store = StoreService.GetSmdStoreById(device.StoreID.Value);
                                var dealer = DealerService.GetById(store.StoreID);
                                if (!devices.Select(t=>t.DeviceID).Contains(device.DeviceID))
                                {
                                    devices.Add(device);
                                }
                                if (!stores.Select(t=>t.StoreID).Contains(store.StoreID)) 
                                { 
                                    stores.Add(store);
                                }
                                if (!dealers.Select(t=>t.DealerID).Contains(dealer.DealerID))
                                {
                                    dealers.Add(dealer);
                                }
                            }
                            stores = stores.Distinct().ToList<t_smd_Store>();
                            dealers = dealers.Distinct().ToList<t_smd_Dealer>();

                            BusinessService.saveProcessRelation(TaskAPI, ass, null, null, null, null, stores, devices, dealers);

                            if (key == Constant.PROCESS_CHANGEOTHER && !TaskAPI.Summary.Contains("退回"))
                            {
                                TaskAPI.Summary = "设备信息区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary)+" - "+ass.BusinessKey;
                            }
                        }
                       
                    }
                    #endregion

                    #region “Data Check”,“Manager Approve”步骤
                    if (TaskAPI.Step == "Data Check" || TaskAPI.Step == "Manager Approve")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "2")
                        {
                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }
                        else
                        {
                            var sdc_logs = Session["StoreDataChangeLog_Device"] as List<t_StoreDataChangeLog>;
                            sdc_logs = sdc_logs.Where(t => t.UserID == UserAPI.UserFullName).ToList();
                            sdc_logs.ForEach(log => log.AssessmentID = ass.ID);
                            Storage.Save(sdc_logs.ToArray());

                            (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).Edit<t_StoreMasterData>(p =>
                            {
                                step = p.Step = TaskAPI.Step;
                            });
                        }
                    }
                    #endregion

                    #region “DMO Commit”步骤
                    if (TaskAPI.Step == "DMO Commit")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            var assessments = (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == TaskAPI.Incident).List<t_Assessment>();

                            #region 变更日志

                            Mapper.CreateMap<t_StoreDataChangeLog, t_smd_StoreDataChangeLog>();

                            var mdc_changelogs = Session["StoreDataChangeLog_Device"] as List<t_StoreDataChangeLog>;

                            List<t_smd_StoreDataChangeLog> smd_changelogs = Mapper.Map<List<t_StoreDataChangeLog>, List<t_smd_StoreDataChangeLog>>(mdc_changelogs);
                            foreach (t_smd_StoreDataChangeLog smd_changelog in smd_changelogs)
                            {
                                smd_changelog.EntityState._FieldState.Remove("LogID");
                            }
                            Storage.Save(Storage.Context3, smd_changelogs.ToArray());

                            #endregion

                            #region 更新主数据
                            foreach (t_StoreDataChangeLog mdc_changelog in mdc_changelogs)
                            {
                                var id = mdc_changelog.DataID;

                                t_smd_Device store = (t_smd_Device._DeviceID == id).ListFirst<t_smd_Device>(Storage.Context3);

                                Type type = store.GetType();

                                PropertyInfo propertyInfo = type.GetProperty(mdc_changelog.FieldName);
                                propertyInfo.SetValue(store, EntityBase.ChangeType(mdc_changelog.AfterValue, propertyInfo.PropertyType), null);

                                Storage.Save(Storage.Context3, store);
                            }

                            #endregion

                            (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).Edit<t_StoreMasterData>(p =>
                            {
                                step = p.Step = "Finish";
                            });
                            BusinessService.SaveChildProcess(TaskAPI, DwzAssessment1.Assessment, "Finish");
                        }
                        else if (DwzAssessment1.Assessment.Opinion == "2")
                        {
                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }
                    }
                    #endregion
                });
                if (DwzAssessment1.Assessment.Opinion != "2")
                {
                    // 变更列表
                    TaskAPI["Content"] = ChangeLogService.GenerateExcel(TaskAPI);
                    flag = TaskAPI.Send();
                }

                Session.Remove("StoreDataChangeLog_Device");

                //如果数据库写入成功且流程发起成功的情况，将业务表数据与流程实例号进行关联
                if (TaskAPI.Step == "Submit Data")
                {
                    (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });

                    (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });
                }
                #endregion
            }
            catch (Exception ex)
            {
                return_msg = ex.Message.Replace("\"", "\\\"");
                Logging.GetLogger().Error("调用BatchDevice.aspx方法Send_Click出错：" + ex);
                flag = false;
            }
            return flag;
        }

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            string return_msg = string.Empty;
            if (Send(ref return_msg))
            {
                btn_submit.Visible = false;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { window.opener.reload(); closeWin(); } });", true);
                return;
            }
            else
            {
                return_msg = string.IsNullOrEmpty(return_msg) ? Resources.Global.C_00_Failed : return_msg;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.prompt('" + return_msg + "','提示', 'info');", true);
                return;
            }
        }

        private void InitDropDownList()
        {
            ConfigService configService = new ConfigService();

            #region 发放方式
            DataTable dt_type = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_FFFS') order by seq").Tables[0];
            DeliveryType.AppendDataBoundItems = true;
            DeliveryType.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_type.Rows)
            {
                DeliveryType.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 调色机型号
            DataTable dt_DispenserModel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_TSJLX') order by seq").Tables[0];
            DispenserModel.AppendDataBoundItems = true;
            DispenserModel.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_DispenserModel.Rows)
            {
                DispenserModel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 震荡机型号

            DataTable dt_ShakerModel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_ZDJLX') order by seq").Tables[0];
            ShakerModel.AppendDataBoundItems = true;
            ShakerModel.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_ShakerModel.Rows)
            {
                ShakerModel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 电脑型号

            DataTable dt_PcModel = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_DNXH') order by seq").Tables[0];
            PcModel.AppendDataBoundItems = true;
            PcModel.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_PcModel.Rows)
            {
                PcModel.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            #region 设备状态
            DataTable dt_Status = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_SBZT') and name not in ('公司大仓','经销商处寄存','报废','E-approve导入无状态','CRM导入无状态') order by seq").Tables[0];
            Status.AppendDataBoundItems = true;
            foreach (DataRow row in dt_Status.Rows)
            {
                Status.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion
        }

        private void InitUpdateLogs()
        {
            if (Session["StoreDataChangeLog_Device"] == null) return;

            var sdc_logs = Session["StoreDataChangeLog_Device"] as List<t_StoreDataChangeLog>;

            Mapper.CreateMap<t_StoreDataChangeLog, StoreDataChangeLogDto>();
            var list = Mapper.Map<List<t_StoreDataChangeLog>, List<StoreDataChangeLogDto>>(sdc_logs);
            IsoDateTimeConverter iso = new IsoDateTimeConverter();
            iso.DateTimeFormat = "yyyy-MM-dd";
            update_logs = JsonConvert.SerializeObject(list, iso);
        }

    }
}